package x.ovo.wechat.bot.core.util;

import lombok.experimental.UtilityClass;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import x.ovo.wechat.bot.core.exception.YamlException;

import java.io.*;
import java.util.Map;

/**
 * yml工具类
 *
 * @author ovo, created by 2024/07/06
 */
@UtilityClass
public class YmlUtil {

    private static final Yaml YAML = new Yaml(new SafeConstructor(new LoaderOptions()));

    public static Map<String, ?> load(File file) {
        try (FileReader reader = new FileReader(file)) {
            return YAML.load(reader);
        } catch (IOException e) {
            throw new YamlException("加载 [" + file.getPath() + "] 失败", e);
        }
    }

    public static <T> T load(File file, Class<T> clazz) {
        try (FileReader reader = new FileReader(file)) {
            return YAML.loadAs(reader, clazz);
        } catch (IOException e) {
            throw new YamlException("加载 [" + file.getPath() + "] 失败", e);
        }
    }

    public static <T> T load(InputStream in, Class<T> clazz) {
        return YAML.loadAs(in, clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(Map<String, ?> map, String path) {
        Object res = null;
        for (String key : path.split("\\.")) {
            if (map.containsKey(key)) {
                res = map.get(key);
                if (res instanceof Map<?, ?>) map = (Map<String, ?>) res;
            } else {
                throw new YamlException("路径 [" + path + "] 不存在");
            }
        }
        return (T) res;
    }

    public static void save(Object object, File file) {
        if (!file.exists()) file.getParentFile().mkdir();
        try (FileWriter writer = new FileWriter(file)) {
            YAML.dump(object, writer);
        } catch (IOException e) {
            throw new YamlException("保存 [" + file.getPath() + "] 失败", e);
        }
    }

}
